<?php
namespace app\admin\controller;
use app\common\controller\AdminBase;
/*员工管理11*/
class Staff extends AdminBase{
	private $user;	
	protected $beforeActionList = [
        'before_index'=>['only'=>'index'],
    ];
	function _initialize() {
		$this->user=new \app\admin\model\User();
		if(!in_array(request()->action(),["qr_down","model_img_down"])){
			parent::_initialize();	
		}
    }
	function index(){
		echo $this->fetch();
	}
	/**
	 * 新增员工
	 */	
	function add(){
		$shop_id=sp_get_current_shop_id();
		if(request()->isPost()){
			$card_no=input("card_no");
			$count=db("Interface")->where("card_no='$card_no' and shop_id=$shop_id")->count(1);
			if($count>0){
				$this->ajax_error("卡号已存在");
			}
		   $data=array(
					"card_no"=>$card_no,
					"in_varifycation"=>input("in_varifycation"),
					"in_varifycation_type"=>input("in_varifycation_type"),
					'fingerprint'=>input("fingerprint"),
					"mobile"=>input("mobile"),
					"name"=>input("name"),
					"descs"=>input("descs"),
					"owner_type"=>2,
					"shop_id"=>$shop_id
			);
			
			if(!empty(input("fingerprint"))&&strlen(input("fingerprint"))>500){//指纹验证
			    $this->_model_down_record_save_update(array("shop_id"=>$shop_id,"card_no"=>$card_no,"type"=>1));
			}
			if(!empty(input("icon1"))&&strlen(input("icon1"))>10){//人脸验证
				 $this->_face_code_insertOrupdate(array(
						  							"card_no"=>$card_no,"face1"=>input("face1"),
						  							"icon1"=>input("icon1"),
						  							"shop_id"=>$shop_id,
						  							));
			}	
			
			action('OptLog/api_add',['member'=>$data,'icon'=>input("icon1")]);	
			db("Interface")->insert($data);
		   return $this->ajax_success("成功");
		}else{
			echo $this->fetch();
		}
	}
	
    /**
	 * 修改员工
	 */
	function edit(){
		$shop_id=sp_get_current_shop_id();
		if(request()->isPost()){
		   $model=db("Interface")->find(input("id"));
		   $old_model=$model;
		   $old_icon=db("FaceCode")->where("shop_id=$shop_id and card_no='".$model['card_no']."'")->value('icon1');
		   $model["in_varifycation"]=input("in_varifycation");
		   $model["in_varifycation_type"]=input("in_varifycation_type");
		   $model["mobile"]=input("mobile");
		   $model["name"]=input("name");
		   $model["descs"]=input("descs");
		   $model["fingerprint"]=input("fingerprint");
		  
			if(!empty(input("fingerprint"))&&strlen(input("fingerprint"))>500){//指纹验证
				$this->_model_down_record_save_update(array("shop_id"=>$shop_id,"card_no"=>$model['card_no'],"type"=>1));
			}
			if(!empty(input("icon1"))&&strlen(input("icon1"))>10){//人脸验证
				 $this->_face_code_insertOrupdate(array(
						  							"card_no"=>$model['card_no'],"face1"=>input("face1"),
						  							"icon1"=>input("icon1"),"shop_id"=>$shop_id
						  							));
			}else{
				db("FaceCode")->where("shop_id=$shop_id and card_no='".$model['card_no']."'")->delete();
			}	
			
			action('OptLog/api_edit',['member'=>$old_model,'icon'=>empty($old_icon)?"":$old_icon,'member1'=>$model,'icon1'=>input('icon1','')]);
			db("Interface")->update($model);
		   return $this->ajax_success("成功");
		
		}else{
			$model=db("Interface")->find(input("id"));
			$this->assign("model",$model);
			$facecode=db("FaceCode")->fetchsql(FALSE)->where(" shop_id=$shop_id and  card_no='".$model['card_no']."'")->find();
			if(empty($facecode)){
				$this->assign("is_bind_face",0);
				$facecode=array("shop_id"=>$shop_id,"face1"=>null,"icon1"=>null);
			}else{
				$this->assign("is_bind_face",1);
			}
			if(empty($model['fingerprint'])){
				$this->assign("is_bind_finger",0);
			}else{
				$this->assign("is_bind_finger",1);
			}
			
			$this->assign("facecode",$facecode);
			$this->assign("borrow_card_no",input("borrow_card_no",""));
			
			$pvalue=db("SystemSet")->where(" shop_id=$shop_id  and code='s_s_6' ")->value("pvalue");
			
			echo $this->fetch();
		}
	}
	
	/**
	 * 删除员工 
	 **/
	function delete(){
		$id=input("id");
		$model=db("Interface")->find($id);
		$card_no=$model['card_no'];
		$shop_id=sp_get_current_shop_id();
		$old_icon=db("FaceCode")->where("shop_id=$shop_id and card_no='$card_no'")->value('icon1');
		$count=db("Interface")->where("original_id=$id and shop_id=$shop_id")->count(1);
		if($count>0){// 存在借卡
		    $this->ajax_error("此员工借卡未还，请先还卡");	
		}
		action('OptLog/api_del',['member'=>$model,'icon'=>empty($old_icon)?'':$old_icon]);
		//清理卡
		db("Interface")->delete($id);
		//清理人脸数据
		db("FaceCode")->where("card_no='$card_no' and shop_id=$shop_id")->delete();
		
		$this->ajax_success("成功");
	}
	
	/*员工卡借卡*/
	function  borrow(){
		if(request()->isPost()){
			$card_no=input("card_no");//借的卡号
			$shop_id=sp_get_current_shop_id();
			$count=db("Interface")->where("card_no='$card_no' and shop_id=$shop_id ")->count(1);
			if($count>0){
				return $this->ajax_error("此卡号已经存在");
			}
			//新增一条借记卡
			db("Interface")->insert(array("shop_id"=>$shop_id,"card_no"=>input("card_no"),"name"=>input("name"),"mobile"=>input("mobile"),"is_original"=>0,"owner_type"=>2,"descs"=>input("descs"),"original_id"=>input("id")));
			//新增一条记录
			db("BorrowCard")->insert(array("shop_id"=>$shop_id,"card_no"=>input("card_no"),"name"=>input("name"),"mobile"=>input("mobile"),"descs"=>input("descs"),"original_card_no"=>input("original_card_no"),"owner_type"=>2));
			return $this->ajax_success("成功");
		}else{
			$id=input('id');
			$shop_id=sp_get_current_shop_id();
			$count=db("Interface")->where("original_id=$id and shop_id=$shop_id and owner_type in(1,2)")->count(1);
			if($count>0){// 存在借卡
			    echo "此员工已经借卡一张，请先归还";	
			    die;
			}
			$model=db("Interface")->find($id);
			$this->assign("model",$model);
			echo $this->fetch();	
		}
	}
	
	/*员工还卡*/
	function  back(){
		if(request()->isPost()){
			$card_no=input("card_no");//借的卡号
			$shop_id=sp_get_current_shop_id();
			//修改借记状态
			db("BorrowCard")->where("card_no='$card_no' and shop_id=$shop_id and is_back=0 ")->update(array("back_time"=>date("Y-m-d H:i:s"),"is_back"=>1));
			//删除借记卡
			db("Interface")->where("card_no='$card_no' and shop_id=$shop_id ")->delete();
			return $this->ajax_success("成功");
		}else{
			$id=input('id');
			$shop_id=sp_get_current_shop_id();
			//借记的卡号
			$borrow_card_no=db("Interface")->where("original_id=$id and shop_id=$shop_id")->value("card_no");
			if(empty($borrow_card_no)){
			    echo "此员工没有借卡，无须还卡";	
			    die;
			}
			$this->assign("borrow_card_no",$borrow_card_no);
			$model=db("Interface")->find($id);
			$this->assign("model",$model);
			echo $this->fetch();	
		}
	}
	/**
	 * 员工换卡 
	 * */
	 function change_card(){
	 	$shop_id=sp_get_current_shop_id();
		if(request()->isPost()){
			$card_no=input("card_no");//新的卡号
			$old_card=input("old_card");//旧的卡号
			$id=input("id");
			$model=db("Interface")->find($id);
			$new_model=$model;$new_model['card_no']=$card_no;
			$old_icon=db("FaceCode")->where("shop_id=$shop_id and card_no='$card_no'")->value('icon1');
			$count=db("Interface")->where("card_no='$card_no' and shop_id=$shop_id")->count(1);
			if($count>0){
				return $this->ajax_error("新卡号已经存在");
			}
			action('OptLog/api_edit',['member'=>$model,'icon'=>empty($old_icon)?"":$old_icon,'member1'=>$new_model,'icon1'=>empty($old_icon)?"":$old_icon]);
			//修改卡号
			db("Interface")->where("id=$id ")->setField(array("card_no"=>$card_no));
			//修改人脸模板卡号
			db("FaceCode")->where("card_no='$old_card' and shop_id=$shop_id ")->fetchsql(FALSE)->setField(array("card_no"=>$card_no));
			return $this->ajax_success("成功");
		}else{
			$id=input('id');
			$count=db("Interface")->where("original_id=$id and shop_id='$shop_id'")->count(1);
			if($count>0){// 存在借卡
			    echo "此员工已经借卡一张，请先归还";	
			    die;
			}
			$model=db("Interface")->find($id);
			$this->assign("model",$model);
			echo $this->fetch();	
		}
	}
	 
	/*员工列表数据*/
	function ajax_index(){
		$this->ajax($this->_ajax_index());
	}
	
	//插入或者修改facecode
	private function _face_code_insertOrupdate($data){
		if(empty($data)){
			return;
		}else{
			$card_no=$data["card_no"];
			$shop_id=$data['shop_id'];
			$model=db("FaceCode")->where(" card_no='$card_no' and shop_id=$shop_id")->find();
			if(empty($model)){//新增
				db("FaceCode")->insert($data);
			}else{//修改
				db("FaceCode")->update(array_merge($model,$data));
			}
			$data['type']=2;
			$data['update_time']=date("Y-m-d H:i:s");
			$this->_model_down_record_save_update($data);
		}
	}
	
	/**
	 * 模板是否新增或者修改---做记录
	 * */
	private function _model_down_record_save_update($data){
		$shop_id=$data['shop_id'];
		$card_no=$data['card_no'];
		$type=$data['type'];
		$model=db("ModelDownRecord")->where("card_no='$card_no' and shop_id=$shop_id and type=$type ")->field("id,card_no")->find();
		if(empty($model)){
			db("ModelDownRecord")->insert(array("card_no"=>$card_no,"shop_id"=>$shop_id,"type"=>$type,"is_down"=>0));
		}else{
			db("ModelDownRecord")->fetchsql(FALSE)->where("card_no='$card_no' and shop_id=$shop_id and type=$type")->update(array("is_down"=>0,"update_time"=>date("Y-m-d H:i:s")));
			$borrow_card_no=db("Interface")->where(" original_id=(select id from m_interface where card_no='$card_no' and shop_id=$shop_id) and shop_id=$shop_id")->value("card_no");
			if(!empty($borrow_card_no)){
				db("ModelDownRecord")->where("card_no='$borrow_card_no' and shop_id=$shop_id")->update(array("is_down"=>0,"update_time"=>date("Y-m-d H:i:s")));
			}
		}
	}
	///////////////////////////////////////////////////////////////////////////////////
	/**
	 * 权限菜单
	 **/
	function before_index(){
		$auth_group=sp_get_auth_menu_3("10041000");
		$this->assign("menus",$auth_group);
	}
	
	/*获取员工数据*/
	private function _ajax_index(){
		$query=array('name'=>array("field" =>"name","operator" =>"="),
					 'card_no'=>array("field" =>"card_no","operator" =>"="),
					 'mobile'=>array("field" =>"mobile","operator" =>"="),
					 );
		$draw=input("draw",0)+1;//请求时间		 
		$where_and=join(" and ",sp_get_param_sql(request()->isPost(),$query));
		$where_and.=" and owner_type=2 and is_original=1 ";
		$shop_id=sp_get_current_shop_id();
		if(!empty($shop_id)){
			$where_and.=" and shop_id=$shop_id";
		}
		//借计卡条件
		if(!empty(input("borrow_card_no"))){
			$original_id=db("Interface")->where("  shop_id=$shop_id and is_original=0 and owner_type=2 and card_no='".input("borrow_card_no")."'")->value("original_id");
			if(empty($original_id)){
				$original_id=0;
			}
			$where_and.=" and  id=".$original_id;
		}
		
		$total=db("Interface")->where($where_and)->fetchsql(FALSE)->count(1);
		$list=db("Interface")->field("fingerprint",true)->where($where_and)->order($this->get_order())->limit($this->get_limit())->fetchsql(FALSE)->select();
		
		$borrow_list=$this->borrow_list();
		foreach ($list as $key => $value) {
			if(isset($borrow_list[$value['id']])){
				$list[$key]["borrow_card_no"]=$borrow_list[$value['id']];
			}else{
				$list[$key]["borrow_card_no"]="";
			}
		}
		return array('pageData'=>$list,'total'=>$total,"draw"=>$draw);
	}
	//获取员工借卡列表
	public function borrow_list(){
		$shop_id=sp_get_current_shop_id();
		return db("Interface")->where("owner_type=2 and shop_id=$shop_id and is_original=0")->column("original_id,card_no");
	}
	//下载二维码
	public function qrcode(){
		$mobile=input("mobile");
		$shop_id=sp_get_current_shop_id();
		$type=input("type",1);//1会员二维码  2员工二维码
        //不带LOGO
        import('phpqrcode.phpqrcode', EXTEND_PATH);
        //生成二维码图片
        $object = new \QRcode();
		if($type==1){
			$url = $mobile." ".date("Y-m-d H:i:s");	
		}elseif($type==2){
			$url = $mobile." 9999-99-99 99:99:99";
		}
        
        $level=4;
        $size=12;
		$path='./data/qrcode/'.$shop_id.'/';
		if(!file_exists($path)){
			mkdir($path,07777,TRUE);
		}
        $file = $path.$mobile.'.png';
        $errorCorrectionLevel =intval($level) ;//容错级别
        $matrixPointSize = intval($size);//生成图片大小
        $object->png($url,  $file, $errorCorrectionLevel, $matrixPointSize, 2);
		
		$this->assign("img",substr($file,1)."?t=".time());
		$this->assign("shop_id",sp_get_current_shop_id());
		$this->assign("file_name",$mobile.'.png');
		echo $this->fetch();
	}
	/**
	 * 二维码下载
	 * */
	public function qr_down(){
		$host=$_SERVER['SERVER_NAME'];
		$shop_id=input("shop_id",0);
		$file_name=input("file_name","");
		if(empty($shop_id)||empty($file_name)){
			echo "非法访问";die;
		}
		$filename = 'http://'.$host.'/data/qrcode/'.$shop_id.'/'.$file_name;
		//指定被下载文件的文件名称
		header("Content-Disposition:attachment;filename=$file_name");
		readfile($filename);
	}
	/**
	 * 人脸模板下载
	 * */
	public function model_img_down(){
		$host=$_SERVER['SERVER_NAME'];
		$img_url=input("img_url");
		$file_name=input("card_no");
		$url='http://'.$host.$img_url;
		header("Content-Disposition:attachment;filename=$file_name".".jpeg");
		readfile($url);		
	}
}
